package com.yjd.api.org;

import com.yjd.comm.base.control.BaseControl;
import com.yjd.comm.base.enums.DbWREnums;
import com.yjd.comm.base.model.IntroDetailModel;
import com.yjd.comm.base.model.PagerModel;
import com.yjd.comm.base.service.ICityService;
import com.yjd.comm.base.service.IIntroDetailService;
import com.yjd.comm.doctor.service.IDoctorService;
import com.yjd.comm.enums.ReferenceTypeEnum;
import com.yjd.comm.org.model.OrganizationModel;
import com.yjd.comm.org.service.IOrganizationService;
import com.yjd.comm.project.model.ProjectModel;
import com.yjd.comm.project.service.IProjectService;
import com.yjd.comm.resource.service.IResourceService;
import com.yjd.comm.tag.model.TagInfoDto;
import com.yjd.comm.tag.service.ITagService;
import com.yjd.comm.util.*;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.annotation.Resource;
import java.util.*;

/**
 * 机构相关处理
 * Created by yangchangyan on 2017/6/29.
 */
@Controller("com.yjd.api.org.OrganizationControl")
@Scope("prototype")
@RequestMapping("/org")
public class OrganizationControl extends BaseControl {

    @Resource
    private IOrganizationService organizationService;

    @Resource
    private IDoctorService doctorService;

    @Resource
    private IIntroDetailService introDetailService;

    @Resource
    private IResourceService resourceService;

    @Resource
    private ICityService cityService;

    @Resource
    private IProjectService projectService;

    @Resource
    private ITagService tagService;

    /**
     * 查询机构所属服务列表
     *
     * @throws
     */
    @RequestMapping(value = "/service/list")
    public void serviceList() throws Exception {
        this.successData(FrameUtil.newHashMap("serviceList", TypeShowUtils.getServiceTypeList()));
    }

    /**
     * 查询机构详情（返回机构详情，该机构的五名主治医师）
     * Created by yangchangyan on 2017/6/29.
     *
     * @param org_id 机构id
     * @return void
     * @throws
     */
    @RequestMapping(value = "/detail", method = RequestMethod.POST)
    public void orgDetail(Long org_id) throws Exception {

        Map<String, Object> paramMap = ServletUtil.getParameterMap(request);

        // 获取机构信息
        List<Map<String, Object>> org = this.queryOrganization(paramMap);
        if (0 == org.size()) {
            FrameUtil.throwBaseException1("机构不存在");
        }

        // 返回结果
        Map<String, Object> orgResult = org.get(0);

        // 获取该机构的级别最高的医生
        paramMap.put("sort", "position desc");
        paramMap.put("page", 1);
        paramMap.put("rows", 5);
        List<Map<String, Object>> specialist = doctorService.queryDoctor(paramMap);
        orgResult.put("specialist", specialist);

        // 机构详情介绍
        IntroDetailModel intro = introDetailService.getModelById(orgResult.get("detail_id"), DbWREnums.READ);
        orgResult.put("detail", null == intro ? "" : intro.getContent());

        paramMap.put("orgInfo", orgResult);
        this.successData(paramMap);
    }

    /**
     * 查询机构，支持分页查询
     * Created by yangchangyan on 2017/7/04.
     *
     * @param regionId 地区ID
     * @param page     查询第page页
     * @param rows     每页展示rows条数据
     * @throws
     */
    @RequestMapping(value = "/all", method = RequestMethod.POST)
    public void allOrganization(Long regionId, Integer page, Integer rows) throws Exception {
        // 如果地区id没有，则默认返回全国范围的机构分布信息
        if (null == regionId) {
            regionId = Long.valueOf(0L);
        }
        Map<String, Object> paramMap = ServletUtil.getParameterMap(request);

        Long category_id = 0L;
        if (null != paramMap.get("category_id")) {
            if (StringUtil.isNotEmpty(paramMap.get("category_id").toString())) {
                try {
                    category_id = Long.parseLong(paramMap.get("category_id").toString());
                } catch (Exception e) {
                    FrameUtil.throwBaseException1("项目分类错误");
                }
            }
        }

        List<ProjectModel> projects = null;
        if (category_id == 0) {
            projects = projectService.getModelList(FrameUtil.newHashMap(), DbWREnums.READ);
        } else {
            projects = projectService.getModelList(FrameUtil.newHashMap("category_id", category_id), DbWREnums.READ);
        }

        // 没有对应分类的项目，直接返回
        if (null == projects || projects.size() == 0) {
            paramMap.put("organization", ArrayUtils.EMPTY_OBJECT_ARRAY);
            this.successData(paramMap);
            return;
        }

        Set<Long> orgIdList = new HashSet<Long>();
        for (ProjectModel p : projects) {
            orgIdList.add(p.getOrg_id());
        }
        paramMap.put("idList", Arrays.asList(orgIdList.toArray()));

        // 返回全国范围的机构分布信息
        if (0 == regionId) {
            paramMap.put("organization", queryOrganization(paramMap));
            paramMap.remove("idList");
            this.successData(paramMap);
            return;
        }

        // 查询所有regionId下面的所有三级城市id
        List<Long> ids = new ArrayList<Long>();
        ids = cityService.querySubCities(regionId, ids);
        paramMap.put("org_city_ids", ids);
        paramMap.put("organization", queryOrganization(paramMap));
        paramMap.remove("org_city_ids");

        paramMap.remove("idList");

        this.successData(paramMap);
    }

    /**
     * 查询属于该机构的项目，支持分页查询
     * Created by yangchangyan on 2017/7/13.
     *
     * @param org_id 机构ID
     * @param page   查询第page页
     * @param rows   每页展示rows条数据
     * @throws
     */
    @RequestMapping(value = "/project", method = RequestMethod.POST)
    public void projectOfOrg(Long org_id, int page, int rows) throws Exception {
        Map<String, Object> paramMap = ServletUtil.getParameterMap(request);
        List<Map<String, Object>> projects = projectService.queryProject(paramMap);
        // 查询项目的负责医生
        List<Map<String, Object>> doctorInfo = null;
        for (Map<String, Object> pro : projects) {
            doctorInfo = doctorService.queryDoctor(FrameUtil.newHashMap("doctor_id", pro.get("doctor_id"), "page", "1", "rows", 1));
            pro.put("doctor", doctorInfo.size() == 0 ? new HashMap<>() : doctorInfo.get(0));
        }
        paramMap.put("project", projects);
        this.successData(paramMap);
    }

    private List<Map<String, Object>> queryOrganization(Map<String, Object> queryParamMap) throws Exception {
        queryParamMap.put("is_used", "1");
        List<Map<String, Object>> orgs = new ArrayList<>();
        PagerModel orgPage = organizationService.getPageModel(queryParamMap, DbWREnums.READ);
        OrganizationModel om = null;
        for (Object obj : orgPage.getDataList()) {
            om = (OrganizationModel) obj;
            Map<String, Object> orgResult = ResultMapBuilder.build(om);

            List<Long> refIdList = new ArrayList<Long>();
            refIdList.add(om.getOrg_id());
            List<TagInfoDto> allTagList = tagService.getTagNameList(FrameUtil.newHashMap("ref_type", ReferenceTypeEnum.ORGANIZATION.getCode(), "idList", refIdList));
            List<String> tags = new ArrayList<String>();
            for (TagInfoDto t : allTagList) {
                tags.add(t.getTag_name());
            }
            orgResult.put("tags", tags);
            orgs.add(orgResult);
        }

        return orgs;
    }

    /**
     * 查询机构，支持分页查询
     *
     * @throws
     */
    @RequestMapping(value = "/all/list", method = RequestMethod.POST)
    public void organizationList(Long regionId) throws Exception {

        Map<String, Object> paramMap = ServletUtil.getParameterMap(request);
        // 如果地区id没有，则默认返回全国范围的机构分布信息
        if (null == regionId) {
            regionId = Long.valueOf(0L);
        }
        // 返回全国范围的机构分布信息
        if (0 == regionId) {
            paramMap.put("organization", queryOrganization(paramMap));
            paramMap.remove("idList");
            this.successData(paramMap);
            return;
        }

        // 查询所有regionId下面的所有三级城市id
        List<Long> ids = new ArrayList<Long>();
        ids = cityService.querySubCities(regionId, ids);
        paramMap.put("org_city_ids", ids);
        paramMap.put("organization", queryOrganization(paramMap));
        paramMap.remove("org_city_ids");
        paramMap.remove("idList");

        this.successData(paramMap);
    }
}
